package com.Venue.controller;

import com.Venue.entity.Venue;
import com.Venue.service.VenueService;
import com.Venue.utils.ResponseResult;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
/**
 * 场地信息 前后端交互类
 */
@RestController
@CrossOrigin
@RequestMapping(value = "/api/venue")
public class VenueController {

    private static final Logger log = LoggerFactory.getLogger(VenueController.class);


    @Autowired
    private VenueService venueService;


    @Value("${server.port}")
    private int serverPort;


    /**
     * 添加场地信息
     */
    @PostMapping("/add.do")
    @CircuitBreaker(name = "venueService", fallbackMethod = "fallbackAddVenue")
    public ResponseResult addVenue(@RequestBody Venue venue) {
        if (venueService.doAddVenueInfo(venue)) {
            return ResponseResult.success("添加场地成功！");
        } else {
            return ResponseResult.failure("添加场地失败！");
        }
    }

    public ResponseResult fallbackAddVenue(@RequestBody Venue venue, Throwable throwable) {
        System.err.println("断路器触发 - 添加场地失败: " + throwable.getMessage());
        return ResponseResult.failure("系统繁忙，请稍后再试");
    }

    /**
     * 修改场地信息
     */
    @PostMapping("/update.do")
    @CircuitBreaker(name = "venueService", fallbackMethod = "fallbackUpdateVenue")
    public ResponseResult updateVenue(@RequestBody Venue venue) {
        if (venueService.doModifyVenueInfo(venue)) {
            return ResponseResult.success("更新场地成功！");
        } else {
            return ResponseResult.failure("更新场地失败！");
        }
    }

    public ResponseResult fallbackUpdateVenue(@RequestBody Venue venue, Throwable throwable) {
        System.err.println("断路器触发 - 更新场地失败: " + throwable.getMessage());
        return ResponseResult.failure("系统繁忙，请稍后再试");
    }

    /**
     * 删除场地信息
     */
    @PostMapping("/delete.do")
    @CircuitBreaker(name = "venueService", fallbackMethod = "fallbackDeleteVenue")
    public ResponseResult deleteVenue(@RequestParam Integer id) {
        Venue venue = new Venue(id);
        if (venueService.doDeleteVenueInfo(venue)) {
            return ResponseResult.success("删除场地成功！");
        } else {
            return ResponseResult.failure("删除场地失败！");
        }
    }

    public ResponseResult fallbackDeleteVenue(@RequestParam Integer id, Throwable throwable) {
        System.err.println("断路器触发 - 删除场地失败: " + throwable.getMessage());
        return ResponseResult.failure("系统繁忙，请稍后再试");
    }

    /**
     * 获取单个场地信息
     */
    @GetMapping("/get.do")
    @CircuitBreaker(name = "venueService", fallbackMethod = "fallbackGetVenue")
    public ResponseResult getVenue(@RequestParam Integer id) {
        Venue paramVenue = new Venue(id);
        Venue venue = venueService.doGetVenueInfo(paramVenue);
        if (venue != null) {
            return ResponseResult.success("获取场地成功！", venue);
        } else {
            return ResponseResult.failure("获取场地失败！");
        }
    }

    public ResponseResult fallbackGetVenue(@RequestParam Integer id, Throwable throwable) {
        System.err.println("断路器触发 - 获取场地失败: " + throwable.getMessage());
        Venue defaultVenue = new Venue();
        return ResponseResult.success("系统繁忙，返回临时数据", defaultVenue);
    }

    /**
     * 获取场地列表（带熔断保护）
     */
    @GetMapping("/list.do")
    @CircuitBreaker(
            name = "venueService",
            fallbackMethod = "fallbackGetVenueList" // 与其他方法保持命名一致
    )
    public ResponseResult getVenueList() {
        log.info("获取场地列表");
        try {
            List<Venue> list = venueService.doGetVenueInfoList();
            return ResponseResult.success("获取场地列表成功！", list);
        } catch (Exception e) {
            log.error("获取场地列表异常", e);
            throw e; // 抛出异常，触发熔断
        }
    }

    public ResponseResult fallbackGetVenueList(Throwable throwable) {
        log.warn("断路器触发 - 获取场地列表失败: {}", throwable.getMessage());
        return ResponseResult.failure("服务暂时不可用，请稍后再试");
    }
    /**
     * 查询场地列表
     */
    @GetMapping("/query.do")
    @CircuitBreaker(name = "venueService", fallbackMethod = "fallbackQueryVenueList")
    public ResponseResult queryVenueList(@RequestBody Venue venue) {
        List<Venue> list = venueService.doQueryVenueInfoList(venue);
        return ResponseResult.success("查询场地列表成功！", list);
    }

    public ResponseResult fallbackQueryVenueList(@RequestBody Venue venue, Throwable throwable) {
        System.err.println("断路器触发 - 查询场地列表失败: " + throwable.getMessage());
        return ResponseResult.success("系统繁忙，返回部分数据", Collections.emptyList());
    }
    // ========== 测试接口（可选） ==========
    @GetMapping("/test-circuit-breaker")
    public ResponseResult testCircuitBreaker() {
        log.info("测试熔断 - 端口: {}", serverPort);
        try {
            List<Venue> list = venueService.doGetVenueInfoList();
            return ResponseResult.build(true, "操作成功（端口：" + serverPort + "）", list);
        } catch (Exception e) {
            return ResponseResult.build(false, "服务暂时不可用（可能触发熔断）", null);
        }
    }
}